import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, Divider, Dropdown, Menu, message, Table, Badge } from 'antd';
import React, { useState, useRef } from 'react';
import { connect, Dispatch, Link } from 'umi';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';

import CreateForm from './components/CreateForm';
import CreateUnit from "./components/CreateUnit";
import UpdateForm, { FormValueType } from './components/UpdateForm';
import { ProjectListItem } from './data';
import { queryProject, updateProject, addProject, removeProject } from './service';
import { StateType } from "./model";

/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields: ProjectListItem) => {
  const hide = message.loading('正在添加');
  try {
    await addProject({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: FormValueType) => {
  const hide = message.loading('正在保存');
  try {
    await updateProject({
      name: fields.name,
      description: fields.description,
      id: fields.id,
    });
    hide();

    message.success('修改成功');
    return true;
  } catch (error) {
    hide();
    message.error('修改失败请重试！');
    return false;
  }
};

/**
 *  删除节点
 * @param selectedRows
 */
const handleRemove = async (selectedRows: ProjectListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await removeProject({
      id: selectedRows.map((row) => row.id),
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

export interface ProjectListProps {
  fetching: boolean;
  adding: boolean;
  projectList: StateType;
  dispatch: Dispatch;
}

const ProjectList: React.FC<ProjectListProps> = (props) => {
  const { dispatch } = props;
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [unitModalVisible, handleUnitModalVisible] = useState<boolean>(false);
  const [unitModalTitle, setUnitModalTitle] = useState<any>("");
  const [unitModalInitValue, setUnitModalInitValue] = useState<any>({});
  const [stepFormValues, setStepFormValues] = useState({});
  const actionRef = useRef<ActionType>();
  const columns: ProColumns<ProjectListItem>[] = [
    {
      title: '项目名称',
      dataIndex: 'name',
      rules: [
        {
          required: true,
          message: '项目名称为必填项',
        },
      ],
    },
    {
      title: '项目描述',
      dataIndex: 'description',
      valueType: 'textarea',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              handleUpdateModalVisible(true);
              setStepFormValues(record);
            }}
          >
            编辑
          </a>
          <Divider type="vertical" />
          <a
            onClick={() => {
              handleUnitModalVisible(true);
              setUnitModalTitle('新增单体工程');
              setUnitModalInitValue({ pid: record.id });
            }}
          >
            添加单体
          </a>
          <Divider type="vertical" />
          <Link to={`/project/${record.id}`}>详情</Link>
        </>
      ),
    },
  ];

  const handleUnitAdd = (params: Object) => {
    dispatch({
      type: 'projectList/unitSave',
      payload: {
        ...params,
      },
      callback: (success) => {
        if (success) {
          handleUnitModalVisible(false);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }
      },
    });
  };

  return (
    <PageHeaderWrapper>
      <ProTable<ProjectListItem>
        headerTitle="项目列表"
        actionRef={actionRef}
        expandable={{
          expandedRowRender: (record) => {
            return (
              <Table
                rowKey="id"
                columns={[
                  {
                    title: '单体名称',
                    dataIndex: 'name',
                  },
                  {
                    title: '建筑',
                    dataIndex: 'jianzhu',
                    render: (item: any) => {
                      switch (item) {
                        case "4":
                          return <Badge status="error" text="审核退回" />;
                        case "3":
                          return <Badge status="success" text="审核通过" />;
                        case "2":
                          return <Badge status="processing" text="审核中" />;
                        case "1":
                          return <Badge status="warning" text="已上传" />;
                        case "0":
                        default:
                          return <Badge status="default" text="未上传" />;
                      }
                    },
                  },
                  {
                    title: '结构',
                    dataIndex: 'jiegou',
                    render: (item: any) => {
                      switch (item) {
                        case "4":
                          return <Badge status="error" text="审核退回" />;
                        case "3":
                          return <Badge status="success" text="审核通过" />;
                        case "2":
                          return <Badge status="processing" text="审核中" />;
                        case "1":
                          return <Badge status="warning" text="已上传" />;
                        case "0":
                        default:
                          return <Badge status="default" text="未上传" />;
                      }
                    },
                  },
                  {
                    title: '给排水',
                    dataIndex: 'jipaishui',
                    render: (item: any) => {
                      switch (item) {
                        case "4":
                          return <Badge status="error" text="审核退回" />;
                        case "3":
                          return <Badge status="success" text="审核通过" />;
                        case "2":
                          return <Badge status="processing" text="审核中" />;
                        case "1":
                          return <Badge status="warning" text="已上传" />;
                        case "0":
                        default:
                          return <Badge status="default" text="未上传" />;
                      }
                    },
                  },
                  {
                    title: '暖通',
                    dataIndex: 'nuantong',
                    render: (item: any) => {
                      switch (item) {
                        case "4":
                          return <Badge status="error" text="审核退回" />;
                        case "3":
                          return <Badge status="success" text="审核通过" />;
                        case "2":
                          return <Badge status="processing" text="审核中" />;
                        case "1":
                          return <Badge status="warning" text="已上传" />;
                        case "0":
                        default:
                          return <Badge status="default" text="未上传" />;
                      }
                    },
                  },
                  {
                    title: '电气',
                    dataIndex: 'dianqi',
                    render: (item: any) => {
                      switch (item) {
                        case "4":
                          return <Badge status="error" text="审核退回" />;
                        case "3":
                          return <Badge status="success" text="审核通过" />;
                        case "2":
                          return <Badge status="processing" text="审核中" />;
                        case "1":
                          return <Badge status="warning" text="已上传" />;
                        case "0":
                        default:
                          return <Badge status="default" text="未上传" />;
                      }
                    },
                  },
                  {
                    title: '最后更新时间',
                    dataIndex: 'updateTime',
                    sorter: true,
                  },
                  {
                    title: '操作',
                    dataIndex: 'option',
                    render: (_, unit) => (
                      <>
                        <a
                          onClick={() => {
                            handleUnitModalVisible(true);
                            setUnitModalTitle('编辑单体工程');
                            setUnitModalInitValue(unit);
                          }}
                        >
                          编辑
                        </a>
                        <Divider type="vertical" />
                        <a>
                          删除
                        </a>
                        <Divider type="vertical" />
                        <Link to={`/project/${unit.id}`}>详情</Link>
                      </>
                    ),
                  },
                ]}
                dataSource={record.unitList}
                pagination={{ pageSize: 5 }}
              />
            );
          },
          rowExpandable: record => record.unitList.length > 0,
        }}
        rowKey="id"
        toolBarRender={(action, { selectedRows }) => [
          <Button type="primary" onClick={() => handleModalVisible(true)}>
            <PlusOutlined /> 新建
          </Button>,
          selectedRows && selectedRows.length > 0 && (
            <Dropdown
              overlay={
                <Menu
                  onClick={async (e) => {
                    if (e.key === 'remove') {
                      await handleRemove(selectedRows);
                      action.reload();
                    }
                  }}
                  selectedKeys={[]}
                >
                  <Menu.Item key="remove">批量删除</Menu.Item>
                  <Menu.Item key="approval">批量审批</Menu.Item>
                </Menu>
              }
            >
              <Button>
                批量操作 <DownOutlined />
              </Button>
            </Dropdown>
          ),
        ]}
        request={(params, sorter, filter) =>
          queryProject({ ...params, sorter, filter }).then((result) => {
            return {
              ...result,
              data: result.data.map((p: ProjectListItem) => {
                return {
                  ...p,
                  jianzhu: 0,
                  jiegou: 0,
                  jipaishui: 0,
                  nuantong: 0,
                  dianqi: 0,
                };
              }),
            };
          })
        }
        columns={columns}
        rowSelection={{}}
      />
      <CreateForm onCancel={() => handleModalVisible(false)} modalVisible={createModalVisible}>
        <ProTable<ProjectListItem, ProjectListItem>
          onSubmit={async (value) => {
            const success = await handleAdd(value);
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="key"
          type="form"
          columns={columns}
          rowSelection={{}}
        />
      </CreateForm>
      <CreateUnit
        initValues={unitModalInitValue}
        visible={unitModalVisible}
        title={unitModalTitle}
        onSave={handleUnitAdd}
        onCancel={() => {
          handleUnitModalVisible(false);
        }}
      />
      {stepFormValues && Object.keys(stepFormValues).length ? (
        <UpdateForm
          onSubmit={async (value) => {
            const success = await handleUpdate(value);
            if (success) {
              handleUpdateModalVisible(false);
              setStepFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setStepFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={stepFormValues}
        />
      ) : null}
    </PageHeaderWrapper>
  );
};

export default connect(
  ({
    projectList,
    loading,
  }: {
    projectList: StateType;
    loading: {
      models: { [key: string]: boolean };
    };
  }) => ({
    projectList,
    loading: loading.models.project,
  }),
)(ProjectList);
